import base64
import json
import os
from openai import OpenAI
import pandas as pd
from datetime import datetime

# 初始化一个空的 DataFrame 来存储日志
log_df = pd.DataFrame(columns=['Timestamp', 'Level', 'Message'])

# 函数用于记录日志到 DataFrame
def log_to_df(level, message):
    global log_df
    new_log = pd.DataFrame({
        'Timestamp': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')],
        'Level': [level],
        'Message': [message]
    })
    log_df = pd.concat([log_df, new_log], ignore_index=True)

# base 64 编码格式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 将xxxx/test.png替换为你本地图像的绝对路径
image_path = "d://自动拍照功能验证照片/186/M5A/TRT00000_V0.1.1_错误码拍照上传功能测试报告20250219 - 副本7581.png"
base64_image = encode_image(image_path)
log_to_df('INFO', f"Encoded image from {image_path}")

# pi_key = os.getenv("DASHSCOPE_API_KEY")

client = OpenAI(
    api_key="sk-d2196c77a3a84b5489094c2cfaf6995d",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
log_to_df('INFO', "OpenAI client initialized")

completion = client.chat.completions.create(
    model="qwen-vl-plus",
    messages=[
        {
            "role": "system",
            "content": [{"type": "text", "text": "You are a helpful assistant."}],
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/png;base64,{base64_image}"
                    },
                },
                {"type": "text", "text": "请问这个图片里是否有楼梯或者台阶等跌落区域，有则回答‘有’，没有则回答‘无’，并告诉我你具体的思考过程和判断过程"},
            ],
        },
    ],
)
log_to_df('INFO', "Completion request sent to OpenAI")

# 打印完整的响应内容
print("完整响应内容:", completion)
print(completion.choices[0].message.content)
log_to_df('INFO', f"Response from OpenAI: {completion.choices[0].message.content}")

# 将日志 DataFrame 写入 CSV 文件
log_df.to_csv('remoteToChat.csv', index=False)
log_to_df('INFO', "Log written to remoteToChat.csv")
